#include "StdSharedMemory.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/ipc.h>
#include <sys/shm.h>



struct StdSharedMemory
{
    int shmID;
    size_t size;
};

Shm *InitShm(const char *pathName, int proj_ID,size_t size)
{
    Shm *m = (Shm*) malloc(sizeof(Shm));
    if(m == NULL)
        return NULL;
    
    key_t key = ftok(pathName,proj_ID);
    if(key < 0)
    {
        perror("ftok");
        free(m);
        return NULL;
    }

    m->shmID = shmget(key, IPC_CREAT | 0777,0);
    if(m->shmID < 0)
    {
        perror("shmget");
        free(m);
        return NULL;
    }

    m->size = size;
    return m;
}

void ReadShm(Shm *m, void *ptr, size_t size)
{
    void *p = shmat(m->shmID,NULL,0);
    if(p == NULL)
    {
        perror("shmat");
        return;
    }

    memcpy(ptr,p,m->size > size ? size : m->size);

    if(shmdt(p) < 0)
    {
        perror("shmdt");
        return;
    }
}

void WriteShm(Shm *m, void *ptr, size_t size)
{
    void *p = shmat(m->shmID,NULL,0);
    if(p == NULL)
    {
        perror("shmat");
        return;
    }

    memcpy(p,ptr,m->size > size ? size : m->size);

    if(shmdt(p) < 0)
    {
        perror("shmdt");
        return;
    }
}

void ClearShm(Shm *m)
{
    if(m == NULL)
        return;

    shmctl(m->shmID,IPC_RMID, NULL);
    free(m);
}
